package com.example.demovote.controller;


import com.example.demovote.entity.Vote;
import com.example.demovote.mapper.VoteMapper;
import com.example.demovote.service.IVoteService;
import com.example.demovote.service.ServiceException;
import com.example.demovote.vo.Result;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 投票系统-题目表-2 前端控制器
 * </p>
 *
 * @author ly
 * @since 2024-03-18
 */
@RestController
@RequestMapping("/demovote/vote")
public class VoteController {

    @Resource
    VoteMapper voteMapper;

    @Resource
    IVoteService voteService;

    @RequestMapping("query")
    List<Vote> query() {
        return voteMapper.select();
    }

    @RequestMapping("create")
    Result create(@Valid Vote vote, Errors errors, String[] iname) {
        if (errors.hasErrors()) {
            return new Result(0, "验证错误！", errors.getAllErrors());
        }
        try {
            voteService.create(vote, iname);
            return new Result(1, "提交投票成功！", null);
        } catch (ServiceException e) {
            errors.reject("iname.error", e.getMessage());
            return new Result(0, "验证错误！", errors.getAllErrors());
        }
    }

    @RequestMapping("find")
    Vote find(int id) {
        return voteMapper.selectById(id);
    }
}

